import { useState, useEffect, useCallback, useRef } from "react";
import { Text, View, StatusBar, ActivityIndicator, TouchableOpacity } from "react-native";
import LinearGradient from "react-native-linear-gradient";

import { useDispatch, useSelector } from "react-redux";
import styles from "./styles";

import config from "@/config";
import globalMethods from "@/GlobalMethodProvider";

import Btn from "@/components/Btn";
import CustomIcon from "@/components/CustomIcon";

import type { StateType } from "./type";
import type { RootState } from "@/store";
import type { HomeProps } from "@/router/routerType";
import useScanQrCode from "@/hooks/useScanQrCode";

/** 主菜单 */
const HomeTest = (props: HomeProps) => {
  const [state, _setState] = useState<StateType>({
    isErr: false,
    loadtip: "系统准备中, 请稍等",
    oldAppData: null
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  // 扫描二维码
  const { gotoScanQrCode, qrCodeRaw } = useScanQrCode();

  useEffect(() => {
    console.log("扫码数据: ", qrCodeRaw);
  }, [qrCodeRaw]);

  const isInit = useRef(false);

  const dispatch = useDispatch();

  const { index: reduxIndex } = useSelector((state: RootState) => state);

  /** 初始化 */
  const init = useCallback(async () => {
    setObjState({ isErr: false });
  }, [setObjState]);

  useEffect(() => {
    init();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const DevComp1 = config.IS_DEBUG ? (
    <View style={{ flexDirection: "row", gap: 10 }}>
      <Btn
        text="跳转扫码页面"
        type="primary"
        onClick={async () => {
          console.log("跳转扫码页面");
          gotoScanQrCode();
        }}
      />
    </View>
  ) : null;

  return (
    <LinearGradient colors={["#c2cac7", "#105d5d"]} style={styles.container}>
      <StatusBar hidden />
      <Text style={styles.title}>扫码订餐</Text>
      <View style={styles.subTitleContainer}>
        <ActivityIndicator animating={!state.isErr} size={30} color="white" />
        <Text style={styles.subTitle}>{state.loadtip}</Text>
        {state.isErr && (
          <TouchableOpacity
            onPress={() => {
              isInit.current = false;
              init();
            }}
          >
            <CustomIcon name="icon-Sync" size={30} color="white" />
          </TouchableOpacity>
        )}
      </View>

      {DevComp1}
    </LinearGradient>
  );
};

export default HomeTest;
